require("../../assets/css/index.less");
require("./addDynamic.less");
// 引入weui
const weui = require("../../assets/lib/weui/weui.min.js");
require("../../assets/lib/weui/weui.min.css");

const dom = require("../../utils/dom.js");
const https = require("../../utils/https.js");
const local = require("../../utils/local.js");
// 判断是否有登录
dom.isToken();
dom.ready(function () {
	// 跳转回去圈子页面
	dom.goTo("#header >span", "social");
	// 输入信息, 字数变化
	dom.$("#myContent").addEventListener("input", function () {
		if (this.value.length > 140) {
			dom.$("#myContent").value = this.value.slice(0, 140);
		}
		dom.$("#txtLength").innerHTML = this.value.length;
	});
	// 获取省份
	let provinceInfo = 510000;
	dom.$("#showProvince").addEventListener("click", function () {
		https.get("/api/shared/province", function (res) {
			let dataArr = res.data.map((v) => {
				return {
					label: v.name,
					value: v.id,
				};
			});
			weui.picker(dataArr, {
				onConfirm: (result) => {
					dom.$("#showProvince").innerHTML = result[0].label;
					provinceInfo = result[0].value;
				},
				title: "请选择省份",
			});
		});
	});

	// 获取城市
	let cityInfo = 110500;
	dom.$("#showCity").addEventListener("click", function () {
		if (provinceInfo) {
			https.get("/api/shared/city?provinceId=" + provinceInfo, function (res) {
				let dataArr = res.data.map((v) => {
					return {
						label: v.name,
						value: v.id,
					};
				});
				weui.picker(dataArr, {
					onConfirm: (result) => {
						dom.$("#showCity").innerHTML = result[0].label;
						cityInfo = result[0].value;
					},
					title: "请选择城市",
				});
			});
		} else {
			alert("请先选择省份");
		}
	});
	// =============================================================
	// 点击加号触发上传文件, 上传图片并渲染在页面中
	let msgObj;
	let imgUrls = [];
	dom.$("#addImgFile").addEventListener("change", function () {
		https.upLoadFile(
			"/api/circles/uploadImg",
			"file",
			this.files[0],
			function (res) {
				let img;
				if (res.errno == 0) {
					imgUrls.push(res.data.url);
					// 遍历
					imgUrls.forEach(function (v) {
						img = document.createElement("img");
						img.src = https.BASE_URL + v;
					});
					dom.$("#imgs").insertBefore(img, dom.$("#imgs label"));
				}
			}
		);
	});
	// 获取省份信息

	// 点击发布动态, 储存信息并跳转
	dom.$("#sureAdd").addEventListener("click", function () {
		// 获取最新msgObj
		msgObj = {
			content: dom.$("#myContent").value || " ",
			releaseProvinceId: provinceInfo,
			releaseCityId: cityInfo,
			imgUrls: imgUrls,
		};
		console.log(msgObj);
		// 发表前需要先判断, 如果图片或者内容为空, 不可以发请求
		if (
			!imgUrls.length &&
			!dom.$("#myContent").value &&
			!cityInfo &&
			!provinceInfo
		) {
			alert("请输入信息");
		} else {
			// 把数组中的图片地址发请求存储
			https.post("/api/circles/opinion", msgObj, function (res) {
				console.log(res.data);
				location.href = "social.html";
			});
		}
	});
});
